# -*- coding:utf-8 -*-

from .models import *
import re, io
from metlib.shell.fileutil import *
from metlib.misc.misc import *
from metlib.misc.download import *
from weblib.django_kits import *

DEBUG_MOLD = parse_bool(os.environ.get('DEBUG_MOLD', 'False'))


def uri2dataset(uri):
    """找出数据uri所属的dataset(db层级)"""
    dsname = uri.split('/', 1)[0]
    try:
        dataset = DataSet.objects.get(pk=dsname)
        return dataset
    except DataSet.DoesNotExist:
        return None


def get_user_data_key(user, datauri):
    return u'%s~~%s' % (user.username, datauri)


def get_company_data_key(company, datauri):
    return u'%s~~%s' % (company.codename, datauri)


def user_owns_data(user, datauri):
    """ 检查用户是否有权访问某数据.
    :returns: True, False, 'NoAccess'
    """
    # db_dataset = uri2dataset(datauri)
    #
    # if hasattr(user, 'data_setting'):
    #     user_data_setting = user.data_setting
    # else:
    #     user_data_setting = None
    #
    # if user.is_company_user and hasattr(user.company, 'data_setting'):
    #     company_data_setting = user.company.data_setting
    # else:
    #     company_data_setting = None
    #
    # # 检查用户是否可以访问此数据集
    # if not db_dataset.public:
    #     can_access = (user_data_setting and db_dataset in user_data_setting.accessible_datasets.all()) \
    #                  or (company_data_setting and db_dataset in company_data_setting.accessible_datasets.all())
    #     if not can_access:
    #         return 'NoAccess'
    #
    # # 检查数据集的是否为免费的
    # if db_dataset.free:
    #     return True
    #
    # minuri = db_dataset.dataset.minimize_uri(datauri)
    # if db_dataset.dataset.is_free(minuri):
    #     return True
    #
    # if user_data_setting and db_dataset in user_data_setting.free_datasets.all():
    #     return True
    #
    # if company_data_setting and db_dataset in company_data_setting.free_datasets.all():
    #     return True
    #
    # # 检查用户的特殊权限
    # if user_data_setting and user_data_setting.ignore_sample:
    #     return True
    #
    # # 检查用户特别拥有的数据
    # user_data_key = get_user_data_key(user, datauri)
    # try:
    #     ud = User_Data.objects.get(pk=user_data_key)
    #     return True
    # except User_Data.DoesNotExist:
    #     if user.is_company_user:
    #         company_data_key = get_company_data_key(user.company, datauri)
    #         try:
    #             cd = Company_Data.objects.get(pk=company_data_key)
    #             return True
    #         except Company_Data.DoesNotExist:
    #             pass

    return True


def user_can_access_dataset(user, dataset):
    if dataset.public:
        return True

    if hasattr(user, 'data_setting'):
        user_data_setting = user.data_setting
    else:
        user_data_setting = None

    if user.is_company_user and hasattr(user.company, 'data_setting'):
        company_data_setting = user.company.data_setting
    else:
        company_data_setting = None

    # 检查用户是否可以访问此数据集
    can_access = (user_data_setting and dataset in user_data_setting.accessible_datasets.all()) \
                 or (company_data_setting and dataset in company_data_setting.accessible_datasets.all())

    return can_access


def update_all_molds():
    """更新所有可用的数据集模板.

    :return:
    """
    mold_root = get_setting('DATASET_MOLD_ROOT')
    if mold_root is None:
        return
    folders = LS(mold_root)
    if DEBUG_MOLD:
        print "Updating dataset molds ..."
    for folder in folders:
        try:
            config_fname = os.path.join(mold_root, folder, 'config')
            if not os.path.exists(config_fname):
                continue
            mold_conf = json.load(io.open(config_fname, encoding='utf-8'), strict=False)
            mold_classname = os.path.join(mold_root, folder, mold_conf['classname'])
            mold_classname = re.sub(r'/', '.', mold_classname)
            if DEBUG_MOLD:
                print "\t%s :" % mold_classname,
            mold_model, created = DatasetMold.objects.get_or_create(name=mold_conf['name'], defaults={'classname': mold_classname})
            mold_model.classname = mold_classname
            mold_model.update()
            for tag_name in mold_model.mold_class.tags:
                get_dataset_tag(tag_name)

            if DEBUG_MOLD:
                print "OK"
        except Exception as e:
            if DEBUG_MOLD:
                print u"Error (%s)" % unicode(e)


def create_dataset(para):
    tmpfname = '/tmp/dataset_para_{:%Y%m%d%H%M%S}_{}'.format(local_now(), BASENAME(para))
    try:
        if isinstance(para, (str, unicode)):
            if re.match(r'^https?://.*', para):
                download(para, tmpfname)
            else:
                CP(para, tmpfname)

            with open(tmpfname) as para_f:
                para = json.load(para_f, strict=False)

        info = para.pop('info', {})
        name = para.pop('name')
        ds, created = DataSet.objects.get_or_create(name=name, defaults=para)
        ds.info = info
        ds.save()
    except Exception as e:
        raise
    finally:
        RM(tmpfname)